package net.omnivention.proxy;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class OmniProxy implements Runnable {
	private static Logger logger = Logger.getLogger(OmniProxy.class);

	private List<Interceptor> interceptors;

	private boolean started = false;

	public OmniProxy() {
		interceptors = new ArrayList<Interceptor>();
	}

	public void addInterceptor(Interceptor i) {
		interceptors.add(i);
	}

	public void run() {
		try {
			ServerSocket ss = new ServerSocket(8000);
			logger.info("Listening on 8000");
			while (true) {
				Socket clientSocket = ss.accept();
				ProxyConnector p = new ProxyConnector(clientSocket,interceptors);
				Thread t = new Thread(p);
				t.start();
			}
		} catch (IOException e) {
			logger.error(e, e);
		}

	}

	public void start() {
		if (!started) {
			started = true;
			Thread t = new Thread(this);
			t.start();
		}else{
			logger.warn("Omniproxy is currently running");
		}
	}

	public static void main(String[] argv) throws Exception {
		OmniProxy p = new OmniProxy();
		p.start();
	}

}
